void draw_wf2d(TH2F* wf2d,const char*sn,string outpng,PMTtest pmtdata){
	int inte_l=pmtdata.GetIntLeft();
	int inte_r=pmtdata.GetIntRight();
	TLine *linel = new TLine(inte_l,1000,inte_l,2000);
	TLine *liner = new TLine(inte_r,1000,inte_r,2000);
	TCanvas *can=new TCanvas("can","can",1200,800);
	can->cd();
	wf2d->Draw("colz");
	wf2d->GetYaxis()->SetTitle("U[mV]");	
	wf2d->GetXaxis()->SetTitle("T[ns]");	
	linel->Draw();
	liner->Draw();
	can->SetLogz();
TPad *mypad1 = new TPad("mypad1","This is mypad1",0.01,0.00,0.95,0.95);
mypad1->Draw();
//mypad1->SetFillColor(11);
mypad1->SetFillStyle(4000);
//pad1->SetFrameFillStyle(4000);
mypad1->cd();
gPad->SetFillStyle(0);
gPad->SetFrameFillStyle(0);
//TLatex *bgtex = new TLatex(.03,.662,"JUNO 20\" PMT Qualification Test ");
//bgtex->Draw();
//bgtex->SetTextColorAlpha(8, 0.176);
//bgtex->SetTextSize(0.1091525);
TString pmtsn="SN:"+string(sn);
TLatex *bgtex1 = new TLatex(.263,.81,pmtsn);
bgtex1->Draw();
bgtex1->SetTextColorAlpha(8, 0.776);
bgtex1->SetTextSize(0.1191525);

	can->SaveAs(outpng.c_str());
delete can;
}

void draw_wf1d(TH1F* wf1d,const char*sn,string outpng,PMTtest pmtdata){
TCanvas *can=new TCanvas("can","can",1200,800);
can->cd();
wf1d->Draw("colz");
//wf1d->GetYaxis()->SetRangeUser(wf1d->GetMinimum()-50,wf1d->GetMaximum()+20);
wf1d->GetYaxis()->SetRangeUser(pmtdata.Getbaseline()-30,pmtdata.Getbaseline()+20);
wf1d->GetYaxis()->SetTitle("U[mV]");	
wf1d->GetXaxis()->SetTitle("T[ns]");
float aptime[20];
TLine *apline[20];
for(int i=0;i<20;i++){
	  aptime[i]=*(pmtdata.Getap_time()+i);
if(aptime[i]>500){
	apline[i]=new TLine(aptime[i],pmtdata.Getbaseline()-100,aptime[i],pmtdata.Getbaseline()+20);	
	apline[i]->Draw("sames");
	}
}

	can->SaveAs(outpng.c_str()); 
delete can;
//for(int i=0;i<20;i++){
//delete [] apline[i];
//}
}

int file_exists(const char *filename)
{
return (access(filename, 0) == 0);
}
float Getcrosstime(vector<int> wframe,float adc_factor){
		double sum = std::accumulate(std::begin(wframe)+0, std::begin(wframe)+200, 0.0);
//		double bsl =  sum / wframe.size();
		double bsl =  adc_factor*sum /200.;
		//	cout<<"bsl"<<bsl<<"p0"<<wframe.size()<<endl;
	 
		float ct=0.;
		for(int i=100;i<wframe.size()-300;i++){
			if(wframe[i]*adc_factor>bsl-5.)continue;
			for(int j=1;j<4;j++){
			if(wframe[i+j]*adc_factor>bsl-5.)continue;
			return i*1.;
			}
		}
return ct;
}
Int_t ProcessOneFile(const char* path, const char* date, const char* gcuid,const char* gcusubid, const char* daq,const char* sn){
	int frame_length=10008;
string inputFilePath = string("/pmtfs/disk02/container_data/container4/test/FADC_Run/") + string(daq) + string("/") + string(gcuid)+string("_")+string(gcusubid) +                 string("_") +string(date)+string("_")+ to_string(frame_length) + string("_")+string(daq);
//inputFilePath="/pmtfs/disk02/container_data/container4/test/FADC_Run/8032/9_1_07-18-2157_1008_8032";
//inputFilePath="/pmtfs/disk02/container_data/container4/test/FADC_Run/7949/7_1_07-18-0437_10008_7949";
//inputFilePath="/pmtfs/disk02/container_data/container4/test/FADC_Run/8077/8_1_07-25-1738_10000_8077";
//inputFilePath="/pmtfs/disk02/container_data/container4/test/FADC_Run/8076/1_0_07-25-1647_10000_8076";
//inputFilePath="/pmtfs/disk02/container_data/container4/test/FADC_Run/8927/7_0_08-29-1438_1008_8927";
    // Open input raw data file and create the read param.
//std::cout<<inputFilePath<<endl;

    ifstream inputFile;
    inputFile.open(inputFilePath,ios::in);
	cout<<"the input fp:"<<inputFilePath<<endl;
    if (!inputFile.is_open())
    {
        cout<<"ERROR - BinFileReadToTreeFile() - Unbal to open the Data File!"<<endl;
        return -1;
    }

  unsigned short oneSamplePoint;  // 10-bit sampling value takes 2 Bytes to store.
  int lengthOfEachWave = __WaveLength;


int fcount=0; //frame count
//vector waveframe(lengthOfEachWave,0);
vector<int> waveframe;
//string dir=string("Analysis_Results/") + string(daq);
//if (_access(dir,0)==-1){
//	string mdstring=string("mkdir -p ")+dir;
//	system(mdstring.c_str());
//	cout<<"new folder generated!"<<endl;
//}
//else {cout<<"add files"<<endl;}
string outputFilePath = string("Analysis_Results/") + string(daq) + string("/") + string(gcuid)+string("_")+string(gcusubid) + string("_") +string(date)+string("_")+ to_string(frame_length) + string("_")+string(daq)+".root";
    TFile * outputAnalysedFile = new TFile(outputFilePath.c_str(),"RECREATE");//why not recreate?
    if (outputAnalysedFile->IsOpen() == kFALSE)
    {
        cout<<"ERROR-RawDataProcess(): Unbal to open the output ROOT File!"<<endl;
        return -1;
    }
    outputAnalysedFile->cd();
	  TTree *waveformtree=new TTree("waveform_anatree","analysis_res");
	  float baseline; //baseline of each waveform
	  float signalpeak=0;
	  float signal_crosstime=0;
	  float signal_risetime=0;
	  float signal_falltime=0;
	  float signal_FWHM=0;
	  float signal_QDC=0;
    float aptime[20]={-1};
    float apcharge[20]={-1};
	  int waveid=-1;

	
	  Int_t cnn_tag=10;   //the classification tag from  CNN
	  //building the branches
	  waveformtree->Branch("framebaseline",&baseline);
     waveformtree->Branch("waveformID",&waveid);
	  waveformtree->Branch("sig_QDC",&signal_QDC);
	  waveformtree->Branch("signalpeak",&signalpeak);
	  waveformtree->Branch("signal_crosstime",&signal_crosstime);
	  waveformtree->Branch("signal_risetime",&signal_risetime);
	  waveformtree->Branch("signal_falltime",&signal_falltime);
	  waveformtree->Branch("signal_FWHM",&signal_FWHM);
	  waveformtree->Branch("cnn_tag",&cnn_tag);
    waveformtree->Branch("afterpulsetime",aptime,"aptime[20]/F");
    waveformtree->Branch("afterpulsecharge",apcharge,"apcharge[20]/F");
    

string outpdf1 = string("Analysis_plots/") + string(daq) + string("/") + string(gcuid)+string("_")+string(gcusubid) +string("_") +string(date)+string("_")+ to_string(frame_length) + string("_")+string(daq)+string("1d.pdf");
	TString outpdf=(outpdf1);
	TString outpdf_start=(outpdf1+"[");
	TString outpdf_end=(outpdf1+"]");
	TCanvas *can1=new TCanvas("can1","canvas1",3200,900);
	can1->cd();
	can1->Print(outpdf_start);


PMTtest pmtdata;
int global_range_id=0;
const float range1_factor=0.12;
float crosstime=0;
float crosstimetmp=0;
int signal_cnn_tag=100;
TH1F *hist_ct=new TH1F("hist_ct","hist_ct",10008,0,10008);
/****************************readin 1000 waveframes to decide the signal window******************/
    for (int jj = 0; jj < 1000; jj++)
    {
//the header of frame
	waveframe.clear();
		for(int ii=0;ii<8;ii++){
            inputFile.read(reinterpret_cast<char*>(&oneSamplePoint),2);     // Using reinterpret_cast to convert binary data.
			oneSamplePoint=__builtin_bswap16(oneSamplePoint);
			if(ii==1)global_range_id=oneSamplePoint%2;
			if(ii==1)global_range_id=oneSamplePoint&0x1;
		}

// the data of one frame
        for (int ii = 0; ii < 10008; ii++)
//        for (int ii = 0; ii < lengthOfEachWave; ii++)
        {
            inputFile.read(reinterpret_cast<char*>(&oneSamplePoint),2);     // Using reinterpret_cast to convert binary data.
			oneSamplePoint=__builtin_bswap16(oneSamplePoint);
			 waveframe.push_back(oneSamplePoint);
        }
//the tail of frame
		for(int ii=0;ii<8;ii++){
            inputFile.read(reinterpret_cast<char*>(&oneSamplePoint),2);     // Using reinterpret_cast to convert binary data.
		oneSamplePoint=__builtin_bswap16(oneSamplePoint);
		}
	if(global_range_id)continue;
	crosstimetmp=Getcrosstime(waveframe,range1_factor); //calculate and fill the tree
	if(crosstimetmp<=10)continue;
//	crosstime+=crosstimetmp;
	hist_ct->Fill(crosstimetmp);
//	cout<<"evt"<<fcount<<"ct"<<crosstimetmp<<endl;
	fcount++;
	}    //end of finding signal window
//	crosstime=crosstime*1./fcount;
//TCanvas *c1=new TCanvas("c1","c1",1200,900);
//c1->cd();
//hist_ct->Draw();
	cout<<"rt"<<hist_ct->GetMaximumBin()<<endl;
//		cout<<"the crosstime:"<<crosstime<<endl;
//	pmtdata.SetSigWindow(int(crosstime)-20,int(crosstime)+60);	
	fcount=0;
	pmtdata.SetIntLeft(hist_ct->GetMaximumBin()-25);
	pmtdata.SetIntRight(hist_ct->GetMaximumBin()+75);
	inputFile.seekg(ios::beg);
//c1->SaveAs("checkct.png");
///*************************************process wavefroms************************************/
    for (int jj = 0; jj < 80000; jj++)
////    //for (int jj = 0; jj < numOfWaveforms; jj++)
    {
if (!inputFile.eof()) {fcount++;}
	waveframe.clear();
    waveid=jj;
//        cout<<"Current File Num:"<<jj<<endl;
		/**********the header of frame*************/
		for(int ii=0;ii<8;ii++){
            inputFile.read(reinterpret_cast<char*>(&oneSamplePoint),2);     // Using reinterpret_cast to convert binary data.
		oneSamplePoint=__builtin_bswap16(oneSamplePoint);
		if(ii==1)global_range_id=oneSamplePoint%2;
		//if(ii==1)global_range_id=oneSamplePoint&0x1;
	//	global_range_id=0;
//cout<<"ggggg"<<global_range_id<<endl;
		}
		/**********the data of frame*************/
        for (int ii = 0; ii < 10008; ii++)
//        for (int ii = 0; ii < lengthOfEachWave; ii++)
        {
            inputFile.read(reinterpret_cast<char*>(&oneSamplePoint),2);     // Using reinterpret_cast to convert binary data.
			oneSamplePoint=__builtin_bswap16(oneSamplePoint);
//  	if(global_range_id)oneSamplePoint=oneSamplePoint/0.8*0.12;
	  waveframe.push_back(oneSamplePoint);
//	cout<<oneSamplePoint<<endl;
        }
		/**********the tail of frame*************/
		for(int ii=0;ii<8;ii++){
		    inputFile.read(reinterpret_cast<char*>(&oneSamplePoint),2);     // Using reinterpret_cast to convert binary data.
		oneSamplePoint=__builtin_bswap16(oneSamplePoint);
		}
//	if(fcount%2000==0)cout<<fcount<<endl;
//  	if(global_range_id)continue;
 // 	cout<<"the bsl"<<global_range_id<<"is  "<<baseline;
//  	cout<<"the min"<<global_range_id<<"is  "<<(baseline/0.12-*min_element(waveframe.begin(), waveframe.end()))<<endl;
  	if(global_range_id)continue;
//	if(!global_range_id)continue;
//	if(!global_range_id)continue;
//cout<<"oneSamplePoint:"<<oneSamplePoint<<"\t"<<"global_range_id"<<global_range_id<<endl;
	ProcessWaveFrametmp(waveframe,pmtdata,range1_factor); //calculate and fill the tree

  if(*min_element(waveframe.begin(), waveframe.end())*0.12<baseline-20 && *max_element(waveframe.begin(), waveframe.end())*0.12>baseline+20){
  float o=0;
  o=(*max_element(waveframe.begin(), waveframe.end())*0.12-baseline)/(baseline- *min_element(waveframe.begin(), waveframe.end())*0.12);
  
//cout<<"the current id:"<<jj<<"  "<<"overshoot rate:"<<o<<endl;
  //if(jj==36){
//  pmtdata.Fillwf1d(waveframe);
  
  }
  if(jj%400==0){pmtdata.Fillwf1d(waveframe);
  can1->cd();
  TH1F htmp;
  htmp=pmtdata.Getwf1d();
  htmp.Draw();
htmp.GetYaxis()->SetRangeUser(pmtdata.Getbaseline()-30,pmtdata.Getbaseline()+20);
htmp.GetYaxis()->SetTitle("U[mV]");	
htmp.GetXaxis()->SetTitle("T[ns]");
float aptime[20];
TLine *apline[20];
for(int i=0;i<20;i++){
	  aptime[i]=*(pmtdata.Getap_time()+i);
if(aptime[i]>500){
	apline[i]=new TLine(pmtdata.Getsignal_crosstime()+aptime[i],pmtdata.Getbaseline()-30,pmtdata.Getsignal_crosstime()+aptime[i],pmtdata.Getbaseline()+20);	
	apline[i]->Draw("sames");
	}
}
  can1->SaveAs(outpdf);
  }
  // for(int kk=0;kk<100;kk++)cout<<"waveform:"<<waveframe[kk]<<endl;
  
 // cout<<"oneSamplePoint:"<<oneSamplePoint*0.12<<endl;
 // outfile << oneSamplePoint*0.12 << endl;
 
	//also the histograms are filled here; The calculation results from charge spectrum 
	waveframe.clear();
// get waveform processing results
 baseline=pmtdata.Getbaseline();
 signalpeak=pmtdata.Getsignalpeak();
 signal_crosstime=pmtdata.Getsignal_crosstime();
 signal_QDC=pmtdata.Getsignal_QDC();
 signal_risetime=pmtdata.Getsignal_risetime();
 signal_falltime=pmtdata.Getsignal_falltime();
 signal_FWHM=pmtdata.Getsignal_FWHM();
 signal_cnn_tag=pmtdata.Getsignal_cnn_tag();
// cout<<"what is it?"<<pmtdata.Getap_time()<<endl;
 for(int zz=0;zz<20;zz++){
 aptime[zz]=*(pmtdata.Getap_time()+zz);
 apcharge[zz]=*(pmtdata.Getap_charge()+zz);
 }


 //cout<<aptime[5]<<endl;
waveformtree->Fill();
}
can1->Print(outpdf_end);
cout<<"the total frame number is:"<<fcount<<endl;
//
//TH2F Hist_pp2d=apd.Getpp2d();
TH2F Hist_wf2d=pmtdata.Getwf2d();
TH1F Hist_wf1d=pmtdata.Getwf1d();
TH1F Hist_ptc=pmtdata.Getptc();
//TH1F Hist_wf1d=apd.Getwf1d();
//TH1F Hist_apt=apd.Getapt();
//Hist_pp2d.Write();
Hist_wf2d.Write();
Hist_ptc.Write();
Hist_wf1d.Write();
//Hist_apt.Write();
//primaryPulseTree->Write("",TObject::kOverwrite);
//afterPulseTree->Write("",TObject::kOverwrite);
waveformtree->Write("",TObject::kOverwrite);
outputAnalysedFile->Close();

if(__save_fig){
string dir=string("Analysis_plots/") + string(daq);
string outfig = string("Analysis_plots/") + string(daq) + string("/") + string(gcuid)+string("_")+string(gcusubid) +string("_") +string(date)+string("_")+ to_string(frame_length) + string("_")+string(daq)+string(".png");
string outfig1d = string("Analysis_plots/") + string(daq) + string("/") + string(gcuid)+string("_")+string(gcusubid) +string("_") +string(date)+string("_")+ to_string(frame_length) + string("_")+string(daq)+string("1d.png");
if(file_exists(dir.c_str())){cout<<"dir existed!"<<dir<<endl;}
else{
const int dir_err = mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (-1 == dir_err)
{
        printf("Error creating directory!n");
            exit(1);
}
}
draw_wf2d(&Hist_wf2d,sn,outfig,pmtdata);
draw_wf1d(&Hist_wf1d,sn,outfig1d,pmtdata);
}
//for(int kk=0;kk<5000;kk++){
//cout<<kk<<" "<<waveframe[kk]<<endl;
//}

  return 0;
  }
